//
//  ViewController.m
//  02-掌握-RunLoop实践
//
//  Created by J on 16/1/27.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"
#import "Thread.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic)  Thread *thread;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    Thread* thread = [[Thread alloc]initWithTarget:self selector:@selector(run) object:nil];
    self.thread = thread;

    [self.thread start];//线程任务执行完就处于消亡状态  attempt to start the thread again'

}


//- (void)run{
//    
//        NSLog(@"%@",[NSThread currentThread]);
//    
////    while (1) {//此方法runLoop会一直进入退出 不会休眠
////        [[NSRunLoop currentRunLoop]run];
////    }
//        NSLog(@"------");
//
//    
//}

//虽然线程不死 但是会一直处理while(1);无法处理其他行为(事件)
//- (void)run{
//    
//    NSLog(@"%@",[NSThread currentThread]);
////    while (1);//当前线程永远在处理这行代码
//  
//    NSLog(@"------");
//
//}

- (void)run{//让线程常驻内存 不会消亡
    
    NSLog(@"%s %@",__FUNCTION__,[NSThread currentThread]);
    [[NSRunLoop currentRunLoop]addPort:[NSPort port] forMode:NSDefaultRunLoopMode];//port相当于source
//    [NSRunLoop currentRunLoop]removePort:<#(nonnull NSPort *)#> forMode:<#(nonnull NSString *)#>;//移除port Loop就会退出
    [[NSRunLoop currentRunLoop] run];//从这句开始开启runLoop无限循环 下面一句就不会再执行了
    NSLog(@"xx");

//    [[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

- (void)test{
    NSLog(@"%s %@",__FUNCTION__,[NSThread currentThread]);
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
 
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
//    [self.thread start];//线程任务执行完就处于消亡状态  attempt to start the thread again'
}

- (void)useImageView{
    //只在NSDefaultRunLoopMode 模式下显示图片 如果滚动textView不显示图片 因为滚动时候处于UITrackingRunLoopMode  默认情况下3s后显示图片
    [self.imageView performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"22"] afterDelay:3.0 inModes:@[NSDefaultRunLoopMode]];

    
}

@end
